const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const { saveUser, getUserByEmail } = require('../utils/storage.cjs');
const router = new Router();

// 通常从环境变量中读取，这里写死作为示例
const JWT_SECRET = 'your-secret-key';
const JWT_EXPIRES_IN = '5h'; // token 有效期，例如 1 小时

const authenticateUser = async (ctx, next) => {
  // 认证逻辑实现
  const token = ctx.headers.authorization?.split(' ')[1]; // Bearer <token>
  if (!token) {
    ctx.throw(401, '未提供 token');
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    ctx.state.user = decoded; // 将解码后的用户信息存入 ctx.state
    await next();
  } catch (err) {
    ctx.throw(401, '无效的 token');
  }
};

router.post('/api/auth/register', async (ctx) => {
  const { email, password, username } = ctx.request.body;

  if (!email || !password || !username) {
    ctx.throw(400, '缺少必要字段');
  }

  const existingUser = await getUserByEmail(email);
  if (existingUser) {
    ctx.throw(409, '邮箱已被注册');
  }

  await saveUser({ email, password, username });
  ctx.status = 201;
  ctx.body = { message: '注册成功' };
});

router.post('/api/auth/login', async (ctx) => {
  const { email, password } = ctx.request.body;
  if (!email || !password) {
    ctx.throw(400, '缺少邮箱或密码');
  }

  const user = await getUserByEmail(email);
  if (!user) {
    ctx.throw(404, '用户不存在');
  }

  if (user.password !== password) {
    ctx.throw(401, '密码错误');
  }

  // 生成 token（不要存储敏感信息在 token 中）
  const token = jwt.sign(
    { id: user.id, email: user.email, username: user.username },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  );

  ctx.status = 200;
  ctx.body = { 
    message: '登录成功', 
    username: user.username,
    email: user.email,
    token // 返回 token 给前端
  };
});

module.exports = {
  router,
  authenticateUser
};